<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-focus="'import'" type="warning" size="small" @click="$router.push('/excel')">excel导入</el-button>
          <el-button v-focus="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-focus="'add'" type="primary" size="small" @click="dialogVisible=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'ascending', order: 'formOfEmployment'}">
          <el-table-column label="序号" width="60" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" sortable prop="formOfEmployment">
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <div class="block">
            <el-pagination
              :current-page="page"
              :page-sizes="[5, 10, 20, 'all']"
              :page-size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="添加"
      :visible.sync="dialogVisible"
      width="60%"
      @close="hClose"
    >
      <empDialog ref="empDialog" @close="dialogVisible = false" @hSuccess="hSuccess" />
    </el-dialog>
    <el-dialog :visible.sync="showDialogRole" width="60%" title="分配权限">
      <assign-role v-if="showDialogRole" :role-id="roleId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeeList } from '@/api/employess'
import employees from '@/constant/employees'
import { delEmployee } from '@/api/employess'
import empDialog from './empDialog'
import AssignRole from './assignRole'
const hireType = {}
employees.hireType.forEach(item => { hireType[item.id] = item.value })
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '',
      showDialogRole: false,
      dialogVisible: false,
      list: [],
      page: 1,
      size: 10,
      total: 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    hAssignRole(id) {
      this.showDialogRole = true
      this.roleId = id
    },
    async hDel(id) {
      this.$confirm('您是否确定删除员工').then(
        () => {
          delEmployee(id)
          if (this.list.length <= 1) this.page--
          this.page = this.page < 1 ? 1 : this.page
          this.getList()
        }
      ).catch(err => err)
    },
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.getList()
      this.dialogVisible = false
    },

    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      if (val === 'all') val = 99999
      this.page = val
      this.getList()
    },
    async getList() {
      const res = await getEmployeeList(this.page, this.size)
      this.list = res.data.rows
      this.total = res.data.total
    },
    hireTypeFormat(num) {
      return hireType[num] || '未知'
    },
    formatData(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      if (!list[0]) return
      const tHeader = Object.keys(list[0]).map(item => {
        return mapInfo[item]
      })
      const data = list.map((item) => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    async handleDownload() {
      //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
      try {
        const res = await getEmployeeList(this.page, this.size)
        if (res.code !== 10000) return
        import('@/vendor/Export2Excel').then(excel => {
        // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          // console.log(excel, 'excel')
          const { tHeader, data } = this.formatData(res.data.rows)
          // const data = []
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error, 'error')
      }
    }
  }
}
</script>
